class MyPromise {
    constructor(ex) {
        // resolved rejected pending
        this.status = "pending"
        // 成功的值
        this.value = undefined
        // 失败的原因
        this.reason = undefined
        // 成功的回调
        this.resolvedCbs = []
        // 失败的回调
        this.rejectedCbs = []
        // 成功处理
        const resolve = (value) => {
            this.value = value
            this.status = "resolved"
            this.resolvedCbs.forEach(cb => {
                cb(value)
            })
        }
        // 失败处理
        const reject = (reason) => {
            this.reason = reason
            this.status = "rejected"
            this.rejectedCbs.forEach(cb => {
                cb(reason)
            })
        }
        ex(resolve, reject)
    }
    then(onResolved, onRejected) {
        onResolved = onResolved ? onResolved : value => value
        onRejected = onRejected ? onRejected : reason => { throw reason }
        return new MyPromise((resolve, reject) => {
            if (this.status === "pending") {
                this.resolvedCbs.push(() => {
                    try {
                        resolve(onResolved(this.value))
                    } catch (err) {
                        reject(err)
                    }
                })
                this.rejectedCbs.push(() => {
                    try {
                        resolve(onRejected(this.reason))
                    } catch (err) {
                        reject(err)
                    }
                })
            } else if (this.status === "resolved") {
                resolve(this.value)
            } else if (this.status === "rejected") {
                reject(this.reason)
            }
        })
    }
}

let p = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(1)
    }, 1000)
})

p.then(value => {
    console.log("value", value)
}).then(value => {
    console.log("value", value)
})
